import React, { Component } from "react";
import { FormComponentProps } from "antd/lib/form";
import { Form, Input, Icon, Button } from "antd";
import "./login.scss";
import loginService from "./LoginService";
import { message } from "antd";
import { observer } from "mobx-react";
import { observable, computed, action } from "mobx";
import { withTranslation, WithTranslation } from 'react-i18next';

function hasErrors(fieldsError: any) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}

interface LoginFormProps extends FormComponentProps, WithTranslation {
  history: any;
  t: any;
  i18n: any;
}

@observer
class LoginPage extends Component<any, any> {
  @observable passwordType: string = "password";

  @computed get passwordIcon() {
    return this.passwordType === "text" ? "eye" : "eye-invisible";
  }

  constructor(props: Readonly<LoginFormProps>) {
    super(props);
  }

  componentDidMount() {
    // To disabled submit button at the beginning.
    this.props.form.validateFields();
  }

  render() {
    const {
      getFieldDecorator,
      getFieldsError,
      getFieldError,
      isFieldTouched
    } = this.props.form;
    const { t } = this.props;

    // Only show error after a field is touched.
    const userNameError =
      isFieldTouched("userName") && getFieldError("userName");
    const passwordError =
      isFieldTouched("password") && getFieldError("password");
    return (
      <div className="login-page">
        <Form onSubmit={this.handleSubmit} className="login-form">
          <div className="title-container">
            {/* <Translation>
              {
                (t) => <h3>{t('login.title')}</h3>
              }
            </Translation> */}
            <h3>{t('login.title')}</h3>
          </div>
          <Form.Item
            validateStatus={userNameError ? "error" : ""}
            help={userNameError || ""}
          >
            {getFieldDecorator("userName", {
              rules: [{ required: true, message: `${t('login.username.required')}` }]
            })(
              <Input
                prefix={<Icon type="user" style={{ color: "#889aa4" }} />}
                placeholder={t('login.username.placeholder')}
              />
            )}
          </Form.Item>
          <Form.Item
            validateStatus={passwordError ? "error" : ""}
            help={passwordError || ""}
          >
            {getFieldDecorator("password", {
              rules: [{ required: true, message: `${t('login.password.required')}` }]
            })(
              <Input
                prefix={<Icon type="lock" style={{ color: "#889aa4" }} />}
                suffix={
                  <Icon
                    type={this.passwordIcon}
                    style={{ color: "#889aa4" }}
                    onClick={this.handlePasswordToggle}
                  />
                }
                type={this.passwordType}
                placeholder={t('login.password.placeholder')}
              />
            )}
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              disabled={hasErrors(getFieldsError())}
              block
            >
              {t('login.submit')}
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }

  handleSubmit = (e: any) => {
    e.preventDefault();
    const { t } = this.props;
    const formData = this.props.form.getFieldsValue();
    console.log(formData);
    loginService.login(formData).then((res: any) => {
      console.log("res is ", res);
      if (res.status === 0) {
        message.info(`${t('login.success')}`);
        this.props.history.push("/dashboard");
      } else {
        message.error(res.msg);
      }
    });
  };

  @action
  handlePasswordToggle = () => {
    this.passwordType = this.passwordType === "password" ? "text" : "password";
  };
}

const LoginForm = Form.create({ name: "login_form" })(withTranslation()(LoginPage));

export default LoginForm;
